﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using SAP.Middleware.Connector;
using System.Configuration;

namespace SAPColumnEntity
{
    public partial class SAPColumnEntityForm : Form
    {
        public SAPColumnEntityForm()
        {
            InitializeComponent();
        }

        private void SAPColumnEntityForm_Load(object sender, EventArgs e)
        {
            try
            {
                string appServerHost = Convert.ToString(ConfigurationManager.AppSettings["AppServerHost"]);
                string systemNumber = Convert.ToString(ConfigurationManager.AppSettings["SystemNumber"]);
                string systemID = Convert.ToString(ConfigurationManager.AppSettings["SystemID"]);
                string user = Convert.ToString(ConfigurationManager.AppSettings["User"]);
                string client = Convert.ToString(ConfigurationManager.AppSettings["Client"]);
                string language = Convert.ToString(ConfigurationManager.AppSettings["Language"]);
                string poolSize = Convert.ToString(ConfigurationManager.AppSettings["PoolSize"]);
                string idleTimeout = Convert.ToString(ConfigurationManager.AppSettings["IdleTimeout"]);
                string sapRouter = Convert.ToString(ConfigurationManager.AppSettings["SAPRouter"]);


                string msg = "AppServerHost: " + appServerHost + Environment.NewLine;
                msg += "SystemNumber : " + systemID + Environment.NewLine;
                msg += "SystemID : " + systemNumber + Environment.NewLine;
                msg += "user : " + user + Environment.NewLine;
                msg += "client : " + client + Environment.NewLine;
                msg += "language : " + language + Environment.NewLine;
                msg += "poolSize : " + poolSize + Environment.NewLine;
                msg += "idleTimeout : " + idleTimeout + Environment.NewLine;
                msg += "sapRouter : " + sapRouter + Environment.NewLine;


                lblMessage.Text = msg;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }

        }

        #region Events
        private void btnCreateEntity_Click(object sender, EventArgs e)
        {
            try
            {
                CreateSAPEntities();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        #endregion


        #region Methods

        protected void CreateSAPEntities()
        {

            RfcDestination oRfcDestination = GetConnection();
            IRfcFunction IRfLock = oRfcDestination.Repository.CreateFunction(txtBAPIName.Text.Trim());


            StringBuilder strMainFile = new StringBuilder();
            StringBuilder strInputParameters = new StringBuilder();
            StringBuilder strOutputParameters = new StringBuilder();
            strMainFile.AppendLine("using System;");
            strMainFile.AppendLine("using System.Collections.Generic;");
            strMainFile.AppendLine("using System.Linq;");
            strMainFile.AppendLine("using System.Text;");
            strMainFile.AppendLine("namespace SAPEntities");
            strMainFile.AppendLine("{");

            strMainFile.AppendLine("public class " + IRfLock.Metadata.Name.Replace(' ', '_') + "Entities");
            strMainFile.AppendLine("{");



            #region Output Parameters

            #endregion

            foreach (IRfcParameter param in IRfLock)
            {
                if (param.Metadata.DataType == RfcDataType.TABLE || param.Metadata.DataType == RfcDataType.STRUCTURE)
                {
                    strMainFile.AppendLine(GetSAPTableOrStructureEntities(param).ToString());
                }
                else
                {
                    strMainFile.AppendLine("public const string " + param.Metadata.Name + ";");
                }

            }
            strMainFile.AppendLine("}");
            strMainFile.AppendLine("}");
            WriteToFile(strMainFile.ToString());
            MessageBox.Show("Entities created for" + Environment.NewLine + txtBAPIName.Text.Trim().ToString());

        }

        protected StringBuilder GetSAPTableOrStructureEntities(IRfcParameter param)
        {

            StringBuilder strEntities = new StringBuilder();

            strEntities.AppendLine("public class " + param.Metadata.Name.Replace(' ', '_') + "Entities");
            strEntities.AppendLine("{");

            IRfcStructure sapStructure = null;
            if (param.Metadata.DataType == RfcDataType.TABLE)
            {
                IRfcTable sapTable = param.GetTable();
                sapStructure = sapTable.Metadata.LineType.CreateStructure();
            }
            else if (param.Metadata.DataType == RfcDataType.STRUCTURE)
            {
                sapStructure = param.GetStructure();
            }


            foreach (IRfcField fld in sapStructure)
            {
                strEntities.Append("public const string");

                string internalName = fld.Metadata.Name;
                string displayName = fld.Metadata.Name.Replace(' ', '_');
                strEntities.AppendLine(" " + displayName + " =  \"" + internalName + "\";" + "//" + fld.Metadata.Documentation);

            }
            strEntities.AppendLine("}");


            return strEntities;


        }

        public void WriteToFile(string content)
        {
            try
            {
                string fileName = GetUniqueFileName();// Environment.CurrentDirectory + "\\" + siteName + "_Entities.txt";
                if (!File.Exists(fileName))
                {

                    StreamWriter sw = File.CreateText(fileName);
                    sw.WriteLine(content);
                    sw.Close();
                }

            }
            catch (Exception ex)
            {

            }
        }

        protected string GetUniqueFileName()
        {
            if (!Directory.Exists(Environment.CurrentDirectory + "\\Entities"))
            {
                Directory.CreateDirectory(Environment.CurrentDirectory + "\\Entities");
            }
            int i = 1;
            string unqFileName = Environment.CurrentDirectory + "\\Entities\\" + "SAPEntities_0" + ".txt";
            while (File.Exists(unqFileName))
            {
                unqFileName = Environment.CurrentDirectory + "\\Entities\\" + "SAPEntities_" + i + ".txt";
                i++;
            }

            return unqFileName;

        }

        protected RfcDestination GetConnection()
        {
            string companyCode = "abap_dev";
            RfcRepository RfcRepository;
            RfcDestination oRfcDestination;
            oRfcDestination = RfcDestinationManager.TryGetDestination(companyCode);

            SAPConfiguration oSapConfiguration = new SAPConfiguration();

            //1: Create and register SAP configuration
            if (oRfcDestination == null)
            {
                try
                {
                    RfcDestinationManager.RegisterDestinationConfiguration(oSapConfiguration);
                }
                catch (Exception ex)
                { }
                oRfcDestination = RfcDestinationManager.GetDestination(companyCode);
            }

            //3: Get repository
            //   RfcRepository = oRfcDestination.Repository;

            return oRfcDestination;
        }

        #endregion





    }
}
